﻿using BBCore.Core.Models.Samples;
namespace BBCore.Application.Samples
{
    public class FlashSaleService : IFlashSaleService
    {
        private readonly IFreeSql FreeSql;
        public FlashSaleService(IFreeSql freeSql)
        {
            FreeSql = freeSql;
        }

        public bool TrySeckill(int productId)
        {
            var product =  FreeSql.Select<HYJ_Product_Seckill>()
               .Where(p => p.Id == productId)
               .First();
            if (product == null || product.Stock <= 0)
            {
                return false;
            }
            var updateCount = FreeSql.Update<HYJ_Product_Seckill>()
                .Set(p => p.Stock - 1) // 生成 SQL：SET Stock = Stock - 1
                .Where(p => p.Id == productId && p.Version == product.Version)
                .ExecuteAffrows();
            return updateCount > 0;
        }
        public HYJ_Product_Seckill GetProduct()
        {
            return FreeSql.Select<HYJ_Product_Seckill>().First();
        }
        public void InitializeData()
        {
            // 先清空已有的商品数据
            FreeSql.Delete<HYJ_Product_Seckill>().Where("1 = 1").ExecuteAffrows();

            // 插入新的商品数据
            var product = new HYJ_Product_Seckill
            {
                Name = "测试商品",                 
                Stock = 10 // 初始库存
            };
            FreeSql.Insert(product).ExecuteAffrows();
        }
    }
}
